package com.ruoyi.exam.service.impl;

import java.util.*;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.exam.domain.CompetitionExam;
import com.ruoyi.exam.domain.CompetitionExamImport;
import com.ruoyi.exam.mapper.CompetitionExamMapper;
import com.ruoyi.exam.service.ICompetitionExamService;
import com.ruoyi.student.mapper.CompetitionStudentMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Validator;


/**
 * 成绩管理Service业务层处理
 * 
 * @author WXY
 * @date 2023-11-21
 */
@Service
public class CompetitionExamServiceImpl implements ICompetitionExamService
{
    private static final Logger log = LoggerFactory.getLogger(CompetitionExamServiceImpl.class);

    @Autowired(required = false)
    private CompetitionExamMapper competitionExamMapper;
    @Autowired(required = false)
    private CompetitionStudentMapper competitionStudentMapper;


    /**
     * 查询成绩管理
     * 
     * @param id 成绩管理主键
     * @return 成绩管理
     */
    @Override
    public CompetitionExam selectCompetitionExamById(Long id)
    {
        return competitionExamMapper.selectCompetitionExamById(id);
    }

    /**
     * 查询成绩管理列表
     * 
     * @param competitionExam 成绩管理
     * @return 成绩管理
     */
    @Override
    public List<CompetitionExam> selectCompetitionExamList(CompetitionExam competitionExam)
    {
        List<CompetitionExam> competitionExams = competitionExamMapper.selectCompetitionExamList(competitionExam);
        for (CompetitionExam student : competitionExams) {
            student.setCompetitionId(competitionStudentMapper.loadCompetitionById(String.valueOf(student.getCompetitionId())));
        }
        return competitionExams ;
    }

    @Override
    public List<CompetitionExamImport> selectCompetitionExamListImport(CompetitionExamImport competitionExamImport) {
        List<CompetitionExamImport> competitionExams = competitionExamMapper.selectCompetitionExamListImport(competitionExamImport);
        for (CompetitionExamImport student : competitionExams) {
            student.setCompetitionId(competitionStudentMapper.loadCompetitionById(String.valueOf(student.getCompetitionId())));
        }
        return competitionExams ;
    }

    /**
     * 新增成绩管理
     * 
     * @param competitionExam 成绩管理
     * @return 结果
     */
    @Override
    public int insertCompetitionExam(CompetitionExam competitionExam)
    {
        competitionExam.setCreateTime(DateUtils.getNowDate());
        return competitionExamMapper.insertCompetitionExam(competitionExam);
    }

    /**
     * 修改成绩管理
     * 
     * @param competitionExam 成绩管理
     * @return 结果
     */
    @Override
    public int updateCompetitionExam(CompetitionExam competitionExam)
    {
        /**
         *  修改考场需要判断修改后的考场信息是否被人占用,若是占用则不能修改
         *  通过是否是有成绩,来判断此次的修改是想要修改考场信息还是修改成绩或审核成绩
         */

       if(competitionExam.getExamScores() == null){
           /**
            * 成绩为空,说明此次修改的目的是变更考场信息
            * 开始判断,新的考场信息是否已经被占用
            */
           Map map = new HashMap<>();
           map.put("examAddress",competitionExam.getExamAddress());
           map.put("examSeatnumber",competitionExam.getExamSeatnumber());
           int examAddressAndSeatnumber  = competitionExamMapper.findExamAddressAndSeatnumber(map);
           if ( examAddressAndSeatnumber !=0 ){
               //返回的结果不是0,则说明新的考场信息已经被占用了,需要重新选择
               return 0;
           }
       }

        competitionExam.setUpdateTime(DateUtils.getNowDate());
        return competitionExamMapper.updateCompetitionExam(competitionExam);
    }

    /**
     * 批量删除成绩管理
     * 
     * @param ids 需要删除的成绩管理主键
     * @return 结果
     */
    @Override
    public int deleteCompetitionExamByIds(Long[] ids)
    {
        return competitionExamMapper.deleteCompetitionExamByIds(ids);
    }

    /**
     * 删除成绩管理信息
     * 
     * @param id 成绩管理主键
     * @return 结果
     */
    @Override
    public int deleteCompetitionExamById(Long id)
    {
        return competitionExamMapper.deleteCompetitionExamById(id);
    }


    /**
     * 批量分配考场信息
     */
    /**
     private static int NUM_OF_EXAMS = 0; // 考场的数量
     private static int SEATS_PER_exam = 0; // 每个考场的座位数量
     private static int NUM_OF_STUDENTS = 0; // 考生数量
     */
    public int updateCompetitionExamByMap(CompetitionExam competitionExam) {
        competitionExam.setCreateTime(DateUtils.getNowDate());
        String competitionId = competitionExam.getCompetitionId();
        int NUM_OF_EXAMS = Integer.parseInt(competitionExam.getExamAddress());
        int SEATS_PER_exam = Integer.parseInt(competitionExam.getExamSeatnumber());
//        System.out.println("分配赛事id:" + competitionId);
//        System.out.println("考场总数:" + NUM_OF_EXAMS);
//        System.out.println("座位数总数:" + SEATS_PER_exam);

        //查询报名此赛事的所有人的身份证号码
        List students1 = competitionStudentMapper.getCernoByCompetitionId(competitionId);
        if( students1.size() <= 0){
            return 99;
        }

        //优先判断 考场总数 * 座位号 是否大于等于 考试人数
        if(!((NUM_OF_EXAMS * SEATS_PER_exam) >= students1.size())){
            return students1.size();
        }

        Map<Integer, List<Integer>> examToSeats = new HashMap<>();
        List<String> examList = new ArrayList<>(); // 新建一个List来存放map
        // 为每个考场分配座位
        for (int i = 0; i < NUM_OF_EXAMS; i++) {
            examToSeats.put(i + 1, new ArrayList<>());
            for (int j = 0; j < SEATS_PER_exam; j++) {
                examToSeats.get(i + 1).add(j + 1); // 分配座位号，从1开始递增
            }
        }
        // 随机分配考生到考场座位
        List<Integer> students = new ArrayList<>();
        for (int i = 0; i < students1.size(); i++) {
            students.add(i + 1);
        }
//        System.out.println(students);
        Collections.shuffle(students); // 随机排列学生列表
        Map<String, String> map = new HashMap<>();
        String s;
        for (int i = 0; i < students.size(); i++) {
            int examRoom = students.get(i) % NUM_OF_EXAMS + 1; // 计算考场号
            List<Integer> seatsInRoom = examToSeats.get(examRoom);
            int seat = seatsInRoom.get((students.get(i) - 1) / NUM_OF_EXAMS); // 在该考场中选择一个座位
//            System.out.println("Student " + students.get(i) + " 考场号 " + examRoom + " 座位号 " + seat);
            map.put("examAddress", String.valueOf(examRoom) + "号考场");
            map.put("examSeatnumber", String.valueOf(seat) + "座位");
            map.put("certno", (String) students1.get(students.get(i)-1));
//            System.out.println("分配考场!!!!!!!!!!!");
//            System.out.println(map);
            competitionExamMapper.updateCompetitionExamByMap(map);
            //清空map,以便下一次使用
            map.clear();
        }
        return 1;
}



    @Override
    public String importsalary(List<CompetitionExam> userList, Boolean isUpdateSupport, String operName) {
        return null;
    }

    @Override
    public String importExam(List<CompetitionExamImport> competitionExamImportList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(competitionExamImportList) || competitionExamImportList.size() == 0) {
            throw new ServiceException("导入成绩数据不能为空！");
        }
        Map map = new HashMap<>();
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CompetitionExamImport examImport : competitionExamImportList) {
            try {
                CompetitionExamImport certnoImport = competitionExamMapper.selectCompetitionExamByCertno(examImport.getCertno());
                if ((!(certnoImport.getCertno().equals("null"))) && (certnoImport.getExamScores() == null || updateSupport)) { //判断是否存在
                    //存在,且成绩为空 或 勾选更新数据
                    map.put("certno", examImport.getCertno());
                    map.put("examCreateBy", operName);
                    map.put("examScores", examImport.getExamScores());
                    competitionExamMapper.updateCompetitionExamByMap(map);
                    successNum++;
                    map.clear();
//                    successMsg.append("<br/>" + successNum + "号: " + examImport.getCertno() + " 成绩上传成功!");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + examImport.getCertno() + " 已存在");
                }

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + successNum + "号: " + examImport.getCertno() + " 成绩上传失败!";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
       }
            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            } else {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条!");
            }
        return successMsg.toString();
    }
}
